package cn.devcat.sso.service.impl;

import java.io.File;
import java.io.FileInputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.devcat.sso.config.exception.DevcatAuthException;
import cn.devcat.sso.config.exception.DevcatUserException;
import cn.devcat.sso.config.security.SecurityMessageUtil;
import cn.devcat.sso.entity.DevcatUser;
import cn.devcat.sso.entity.DevcatUserInfo;
import cn.devcat.sso.enums.GenderEnum;
import cn.devcat.sso.mapper.DevcatUserInfoMapper;
import cn.devcat.sso.service.IDevcatUserInfoService;
import cn.devcat.sso.util.UserUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class DevcatUserInfoServiceImpl extends ServiceImpl<DevcatUserInfoMapper, DevcatUserInfo> implements IDevcatUserInfoService {

	@Autowired
	UserUtil userUtil;

	@Value("${devcat.save-file-path}")
	private String saveFilePath;

	/**
	 * 注册用户后的初始化过程
	 */
	@Override
	public void initUserByRegister(DevcatUser user) {
		DevcatUserInfo info = new DevcatUserInfo();
		info.setId(user.getId());
		info.setNickName(user.getUsername());
    info.setAvatar("/data/res/img/init_avatar.png");
		info.setUsername(user.getUsername());
		info.setGender(GenderEnum.SECRET.code());
		save(info);
	}

	/**
	 * 更新头像，这里用base64
	 * @throws DevcatUserException
	 */
	@Override
	public void updateAvatar(MultipartFile file) throws DevcatUserException {
		DevcatUser userByRequest = userUtil.getUserByRequest();
		String avatarDirName = "user_avatars";
		String fullDirPath = saveFilePath+File.separator+avatarDirName;
		File avatarDirFile = new File(fullDirPath);
		if(!avatarDirFile.exists()) {
			avatarDirFile.mkdirs();
		}
		File saveFile = new File(fullDirPath+File.separator+userByRequest.getUsername()+".png");
		try {
			file.transferTo(saveFile);
		} catch (Exception e) {
			e.printStackTrace();
			throw new DevcatUserException("头像保存失败");
		}
		update(new UpdateWrapper<DevcatUserInfo>().eq("id", userByRequest.getId()).set("avatar", saveFile.getPath()));
	}

	/**
	 * 更新用户信息
	 * @throws DevcatUserException
	 */
	@Override
	public void setUserInfo(DevcatUserInfo userInfo) throws DevcatUserException {
		// TODO Auto-generated method stub
		DevcatUser userByRequest = userUtil.getUserByRequest();
		if(!userInfo.getId().equals(userByRequest.getId())) {	//校验token解析出来的userId与传递的userId是否相同，防止其他人恶意调用
			throw new DevcatAuthException(SecurityMessageUtil.BAD_CALL);
		}
		if(userInfo.getBirthday()!=null) {
			int age = userUtil.getAge(userInfo.getBirthday());
			userInfo.setAge(age);
		}
		updateById(userInfo);
	}

	@Override
	public byte[] getAvatar() throws DevcatUserException {
		String userId = userUtil.getUserByRequest().getId();
		return getUserAvatar(userId);
	}

	@Override
	public byte[] getAvatar(String userId) throws DevcatUserException {
		return getUserAvatar(userId);
	}

	private byte[] getUserAvatar(String userId) throws DevcatUserException {
		log.info("get user:{} avatar",userId);
		String avatarPath = getById(userId).getAvatar();
		try {
			FileInputStream fileInputStream = new FileInputStream(avatarPath);
			byte[]bytes = new byte[fileInputStream.available()];
			fileInputStream.read(bytes, 0, fileInputStream.available());
			return bytes;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new DevcatUserException("获取头像失败");
		}
	}


}

